<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>实时聊天应用 - 聊天界面</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        dark: '#1E293B',
                        light: '#F8FAFC'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .chat-height {
                height: calc(100vh - 12rem);
            }
        }
    </style>
</head>
<body class="bg-gray-100 font-sans text-gray-800">
<!-- 聊天页面 -->
<div id="chat-page" class="h-screen flex flex-col bg-gray-50">
    <!-- 顶部导航 -->
    <header class="bg-white shadow-sm py-3 px-6 flex justify-between items-center">
        <div class="flex items-center gap-3">
            <button id="back-to-users" class="text-gray-600 hover:text-primary transition-colors">
                <i class="fa fa-arrow-left"></i>
            </button>
            <h1 id="chat-user-name" class="text-xl font-bold text-dark"></h1>
        </div>
        <div>
            <button id="logout-btn-chat" class="text-gray-500 hover:text-red-500 transition-colors">
                <i class="fa fa-sign-out"></i>
            </button>
        </div>
    </header>

    <!-- 聊天消息区域 -->
    <div id="messages-container" class="flex-1 overflow-y-auto p-4 space-y-4 chat-height">
        <!-- 消息将通过JS动态添加 -->
        <div class="text-center text-gray-500 py-4">
        </div>
    </div>

    <!-- 输入区域 -->
    <div class="bg-white p-4 border-t border-gray-200">
        <form id="message-form" class="flex gap-2">
            <input type="text" id="message-input" placeholder="输入消息..."
                   class="flex-1 px-4 py-2 rounded-full-lg border border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all">
            <button type="submit" class="bg-primary hover:bg-primary/90 text-white p-2 px-4 rounded-lg transition-all transform hover:scale-105 active:scale-95">
                <i class="fa fa-paper-plane"></i>
            </button>
        </form>
    </div>
</div>

<script>
    // 全局变量
    const BACK_ADDRESS_PORT = '47.121.204.23:8081';
    let token = localStorage.getItem('token');
    let currentUserId = localStorage.getItem('currentUserId');
    let currentUserName = localStorage.getItem('currentUserName');
    let targetUserId = localStorage.getItem('targetUserId');
    let targetUserName = localStorage.getItem('targetUserName');
    let websocket = null;
    let messageMap = new Map();

    // DOM元素
    const messagesContainer = document.getElementById('messages-container');
    const messageForm = document.getElementById('message-form');
    const messageInput = document.getElementById('message-input');
    const backToUsersBtn = document.getElementById('back-to-users');
    const logoutBtnChat = document.getElementById('logout-btn-chat');
    const chatUserNameEl = document.getElementById('chat-user-name');

    // 页面初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 检查登录状态和目标用户信息
        if (!token || !currentUserId || !targetUserId || !targetUserName) {
            // 信息不全，跳转到用户列表
            window.location.href = 'userList.html';
            return;
        }

        // 显示聊天对象名称
        chatUserNameEl.textContent = targetUserName;

        // 连接WebSocket
        connectWebSocket();

        // 事件监听
        backToUsersBtn.addEventListener('click', function() {
            window.location.href = 'userList.html';
        });
        logoutBtnChat.addEventListener('click', handleLogout);
        messageForm.addEventListener('submit', handleSendMessage);
    });

    // 登出处理
    function handleLogout() {
        // 关闭WebSocket连接
        closeWebSocket();

        // 清除本地存储
        localStorage.removeItem('token');
        localStorage.removeItem('currentUserId');
        localStorage.removeItem('currentUserName');
        localStorage.removeItem('targetUserId');
        localStorage.removeItem('targetUserName');

        // 跳转到登录页面
        window.location.href = 'login.html';
    }

    // 连接WebSocket
    function connectWebSocket() {
        if (!token || !targetUserId) return;

        // 关闭已有的连接
        closeWebSocket();

        // 创建新连接
        const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        const wsUrl = wsProtocol + '//' + BACK_ADDRESS_PORT + '/ws/chat?targetId=' + targetUserId + '&Authorization=' + encodeURIComponent(token);

        try {
            websocket = new WebSocket(wsUrl);

            websocket.onopen = function() {
                console.log('WebSocket连接已建立');
            };

            websocket.onmessage = function(event) {
                console.log('收到消息:', event.data);

                // 检查是否是Blob对象，如果是则先转换为文本
                if (event.data instanceof Blob) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        processMessage(e.target.result);
                    };
                    reader.readAsText(event.data);
                } else {
                    // 如果是文本直接处理
                    processMessage(event.data);
                }
            };

            websocket.onerror = function(error) {
                console.error('WebSocket错误:', error);
                messagesContainer.innerHTML += '<div class="text-center text-red-500 text-sm py-2">连接出错，请刷新页面重试</div>';
                scrollToBottom();
            };

            websocket.onclose = function() {
                console.log('WebSocket连接已关闭');
                messagesContainer.innerHTML += '<div class="text-center text-orange-500 text-sm py-2">连接已断开，正在尝试重连...</div>';
                scrollToBottom();

                // 3秒后尝试重连
                setTimeout(connectWebSocket, 3000);
            };
        } catch (error) {
            console.error('创建WebSocket连接失败:', error);
            messagesContainer.innerHTML = '<div class="text-center text-red-500 text-sm py-4">无法建立连接，请刷新页面重试</div>';
        }
    }

    // 处理收到的消息
    function processMessage(messageData) {
        try {
            const result = JSON.parse(messageData);

            if (Array.isArray(result)) {
                // 遍历消息并添加到DOM
                result.forEach(function(item) {
                    if(item.id && !messageMap.has(item.id)){
                        addMessageToDOM({
                            id: item.id,
                            fromId: item.fromId,
                            targetId: item.targetId,
                            content: item.content
                        });
                    }
                });
            }
        } catch (error) {
            console.error('解析消息失败:', error);
            // 尝试直接显示原始消息
            addMessageToDOM({
                fromId: 'system',
                content: '收到未知格式消息: ' + messageData
            });
        }
    }

    // 关闭WebSocket连接
    function closeWebSocket() {
        if (websocket) {
            websocket.close();
            websocket = null;
        }
    }

    // 发送消息
    function handleSendMessage(e) {
        e.preventDefault();

        const content = messageInput.value.trim();
        if (!content || !websocket || websocket.readyState !== WebSocket.OPEN) {
            return;
        }

        // 发送消息
        websocket.send(content);

        // 清空输入框
        messageInput.value = '';
    }

    // 添加消息到DOM
    function addMessageToDOM(message) {
        messageMap.set(message.id, message);
        const isOwnMessage = message.fromId == currentUserId;

        const messageEl = document.createElement('div');
        // 为整个消息容器添加对齐类和间距
        messageEl.className = `flex ${isOwnMessage ? 'justify-end' : 'justify-start'} mb-4`;

        messageEl.innerHTML = `
        ${isOwnMessage ? '' : `
            <div class="ml-2 w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center text-gray-600">
                <i class="fa fa-user"></i>
            </div>
        `}
        <div class="${isOwnMessage ? 'bg-primary text-white' : 'bg-white text-gray-800'} rounded-lg px-4 py-2 max-w-[70%] shadow-sm">
            <p>${message.content}</p>
        </div>
        ${isOwnMessage ? `
            <div class="mr-2 w-8 h-8 rounded-full bg-primary/20 flex items-center justify-center text-primary">
                <i class="fa fa-user"></i>
            </div>
        ` : ''}
    `;

        messagesContainer.appendChild(messageEl);

        // 滚动到底部
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }
</script>
</body>
</html>
